<?php
// Database initiation. Creates the correct tables and fields. Probably some records in the future as well but let's start with tables and fields, okay?

$DECKROOT = getcwd(); 

require $DECKROOT . '/config/config.php';
include $DECKROOT . '/classes/database/'.$dbType.".php";

$conn = new mysqli($dbHost,$dbUser,$dbPass,$dbName);

$createQuery = array();

/* check connection */
if (mysqli_connect_errno()) {
	error_log ("Connect failed: %s\n " . mysqli_connect_error());
	exit();
}

$createTableQuery = array(
		array("table" => "pmtdeck", "query" => "CREATE TABLE pmtdeck (id MEDIUMINT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50), description VARCHAR(2500), shortDescription CHAR(144), status TINYINT UNSIGNED, themeID MEDIUMINT UNSIGNED);"),
		array("table" => "pmtcard", "query" => "CREATE TABLE pmtcard (id MEDIUMINT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50), description VARCHAR(2500), shortDescription CHAR(144), status TINYINT UNSIGNED, stackID MEDIUMINT UNSIGNED,parentID MEDIUMINT UNSIGNED,value MEDIUMINT UNSIGNED,assignedTo MEDIUMINT UNSIGNED,effort MEDIUMINT UNSIGNED);"),
		array("table" => "pmtstack", "query" => "CREATE TABLE pmtstack (id MEDIUMINT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50), description VARCHAR(2500), shortDescription CHAR(144), status TINYINT UNSIGNED, deckID MEDIUMINT UNSIGNED);"),
);

error_log (count($createTableQuery)." tables to be created"."\r\n\r\n");

foreach ($createTableQuery as $query) {
	$tableName = $query [ 'table' ];

	$Result=$conn->query("SHOW TABLES LIKE '".$tableName."';");
	if(mysqli_num_rows($Result)==1) {
		error_log ("Table " . $tableName . " exists already.\r\n\r\n");
	}
	else {
		error_log ("Table " . $tableName . " does not exist yet. Creating.\r\n");
		$createQuery = $query [ 'query' ];

		if($conn->query($createQuery)){
			error_log ("Table " . $tableName . " succesfully created table. \r\n\r\n") ;
		} else {
			error_log ("Table " . $tableName . " not created! Something went wrong! \r\n\r\n");
		}
	}
}


/* commit transaction */
if (!$conn->commit()) {
	error_log ("Transaction commit failed\n");
	exit();
}

$conn->close();

echo "All done!";

?>